package com.cheyun.netsalev3.view

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.widget.LinearLayout
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.utils.BaseActivity
import com.just.agentweb.AgentWeb
import android.text.TextUtils
import android.webkit.WebView
import com.cheyun.netsalev3.tencenttim.utils.DemoLog
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.api.ApiStores
import com.just.agentweb.WebChromeClient
import java.net.URLEncoder
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.*
import android.print.PrintAttributes
import android.print.PrintManager
import android.util.Log
import android.webkit.JavascriptInterface
import com.cheyun.netsalev3.adapter.MyPrintAdapter
import com.cheyun.netsalev3.databinding.ActivityDriveCalcBinding
import com.cheyun.netsalev3.utils.DownloadUtil
import com.cheyun.netsalev3.utils.KeyBoardListener
import com.just.agentweb.WebViewClient
import com.tbruyelle.rxpermissions3.RxPermissions
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.yxing.ScanCodeConfig
import com.yxing.def.ScanMode
import com.yxing.def.ScanStyle
import java.io.File


class DriveCalcActivity : BaseActivity<ActivityDriveCalcBinding>() {
    override fun initContentView(): Int {
        return R.layout.activity_drive_calc
    }
    private var pdfUrl:String = ""

    override fun initView() {
//        binding.leftBut.setOnClickListener {
//            finish()
//        }
//        bind
        KeyBoardListener.getInstance(this).init()
    }

    override fun initData() {
        var cauthkey = MySharedPreferences.getCauthkey()
        cauthkey = URLEncoder.encode(cauthkey)

        var url = ApiStores.ANALYSIS_URL+"/calculator?cauthkey="+cauthkey

        var mAgentWeb = AgentWeb.with(this)//传入Activity
                .setAgentWebParent(binding.llWebview,  LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                .useDefaultIndicator()
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
                .ready()
                .go( url)


        DemoLog.i("DriveCalcActivity",ApiStores.ANALYSIS_URL+"/calculator?cauthkey="+cauthkey)

        mAgentWeb.webCreator.webView.setWebChromeClient(object : WebChromeClient() {
             override fun onReceivedTitle(view: WebView, title: String) {
                if (!TextUtils.isEmpty(title)) {
                    binding.headview.titleText?.text = title
                }
                super.onReceivedTitle(view, title)
            }

            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                DemoLog.i("DriveBlockActivity","newProgress:"+newProgress)
                mAgentWeb.indicatorController.setProgress(newProgress)
            }
        })

        mAgentWeb.webCreator.webView.settings.javaScriptEnabled = true
        mAgentWeb.webCreator.webView.addJavascriptInterface(this, "callAndroid")
    }

    private val mWebViewClient = object : WebViewClient() {
        override  fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
            DemoLog.i("DriveBlockActivity","url:"+url)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    private var handler: Handler = object:Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            if(msg?.what == 0){
                doPrintPdf()
            }
//            if(msg?.what == 1){
//                doShare()
//            }
        }
    }

    @JavascriptInterface
    fun print(pdf:String){
        DemoLog.d("drivecalc print",pdf)
        this.pdfUrl = pdf
        handler.sendEmptyMessage(0)
    }

    fun doPrintPdf(){
        RxPermissions(this).requestEach(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE
        ).subscribe {
            if (it.granted) {
                var name = "购车计算器"
                DownloadUtil.get().download(pdfUrl,
                        Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download",
                        name+ ".pdf", object : DownloadUtil.OnDownloadListener {
                    override fun onDownloadSuccess(file: File) {
                        DemoLog.v("DOWN", "下載成功,文件已存入手机内部存储设备根目录下Download文件夾中")
                        val printManager = this@DriveCalcActivity?.getSystemService(Context.PRINT_SERVICE) as PrintManager?
                        val builder = PrintAttributes.Builder()
                        builder.setColorMode(PrintAttributes.COLOR_MODE_COLOR)
                        printManager!!.print(name, MyPrintAdapter(this@DriveCalcActivity, file.path, name), builder.build())
                        Looper.prepare()//增加部分
                        Looper.loop()//增加部分
                    }

                    override fun onDownloading(progress: Int) {
                        DemoLog.v("DOWN", "下載進度$progress")
                    }

                    override fun onDownloadFailed(e: Exception) {
                        DemoLog.v("DOWN", e.toString())
                    }
                })
            } else if (it.shouldShowRequestPermissionRationale) {
                DemoLog.e("camera", "shouldShowRequestPermissionRationale");
            } else {
                DemoLog.e("camera", "error");
                MyToast("请确认是否已禁止应用使用手机存储功能")
            }
        }
    }

    @JavascriptInterface
    fun share(title:String,desc:String,image:String,url:String){
        DemoLog.d("drivecalc share",title+","+desc+","+image+","+url)
        this.imgurl = image
        this.title = title
        this.desc = desc
        this.path = url
        handler.sendEmptyMessage(1)
    }

    var imgurl:String = ""
    var path: String = ""
    var title:String = ""
    var desc:String = ""

//    fun doShare(){
//        var imageurl: UMImage? = null
//        if (TextUtils.isEmpty(imgurl)) {
//            val bmp = BitmapFactory.decodeResource(resources, R.drawable.logo)
//            imageurl = UMImage(this, bmp)
//        } else {
//            imageurl = UMImage(this, imgurl)
//        }
//
//        val web = UMWeb(path)
//        web.setTitle(title)
//        web.setThumb(imageurl)
//        web.description = if (desc == "") path else desc
//        val action = ShareAction(this).withMedia(web).setCallback(shareListener)
//        action.setPlatform(SHARE_MEDIA.WEIXIN).share()
//    }
//
//    private val shareListener = object : UMShareListener {
//
//        override fun onStart(share_media: SHARE_MEDIA) {
//
//        }
//
//        override fun onResult(platform: SHARE_MEDIA) {
//            //            showMsg("分享成功");
//            // showImageMsg((RelativeLayout)findViewById(R.id.detail_linear),R.mipmap.icon_fengxiang_true);
//        }
//
//        override fun onError(platform: SHARE_MEDIA, t: Throwable) {
//            Log.e("detail activity", t.message)
//            //            showMsg("分享失败");
//            //            showImageMsg((RelativeLayout)findViewById(R.id.detail_linear),R.mipmap.icon_fengxiang_false);
//        }
//
//        override fun onCancel(platform: SHARE_MEDIA) {
//            //            showMsg("取消分享");
//            //            showImageMsg((RelativeLayout)findViewById(R.id.detail_linear),R.mipmap.icon_fengxiang_false);
//        }
//    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == ScanCodeConfig.QUESTCODE && data != null) {
            val extras = data.extras
            if (extras != null) {
                val code = extras.getString(ScanCodeConfig.CODE_KEY)
                DemoLog.i("",String.format("%s%s", "结果： ", code))
            }
        }
    }
}
